import React,{ Component } from 'react';
import './data-mgt.css';
import { Button, message, Input, Table, Modal, Breadcrumb } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import LinkButton from '../../components/link-button/linkButton.jsx';
import UploadDatafile from '../../components/Modal/upload-datafile';
import { Link } from 'react-router-dom';
import {getWorkshop,getWells,setWells } from '../../utils/storageUtils';
import {reqDataFileListById,reqDocNameSearch,reqDeleteDoc,reqEditDocInfo} from '../../api';
import Axios from 'axios';
import EditDataFileForm from '../../components/Modal/edit-datafile-form';
import editIcon from '../../assets/image/edit.png'
import deleteIcon from '../../assets/image/delete.png'
const { Search } = Input;
const { confirm } = Modal;

class ShowDataMgt extends Component {

  state = {
    dataFileList:[],
    visible: '0',  
    loading: false,
    form:new FormData(),
  }

  handleNameSearch = async(value) => {   // 按姓名查找  vvvvvvvvvvvvvvvvvvv
    const drill_id = getWells().drill_id;  
    const org_id = getWells().drill_org_id; 
    const ws_id = getWells().drill_ws_id; 
    const doc_name = value;
    const result = await reqDocNameSearch(drill_id,org_id,ws_id,doc_name);
    if(result.code === 200){
      const dataFileList = result.data;
      this.setState({
        dataFileList
      })
    }else{
      message.error(result.data);
    } 
  };

  initColumns = () => {
    this.columns = [
      { title: '数据文件名称', dataIndex: 'doc_name', key: 'doc_name' ,
        sorter: {
          compare: (a,b)=>a.name.localeCompare(b.name),   
        },
      },
      { title: '起始深度', dataIndex: 'start_depth', key: 'start_depth'},
      { title: '终止深度', dataIndex: 'end_depth', key: 'end_depth'},
      { title: '测井操作员', dataIndex: 'operator', key: 'operator'},
      { title: '测量时间', dataIndex: 'measuring_time', key: 'measuring_time'},
      { title: '测量地址', dataIndex: 'measuring_address', key: 'measuring_address'},
      { title: '套管深度', dataIndex: 'casing_depth', key: 'casing_depth'},
      { title: '备注', dataIndex: 'remark', key: 'remark'},
      {
        title: '操作',
        dataIndex: '',
        key: 'dataaction',
        width: 140,
        render: (docInfor) => (
          <span>
            <LinkButton onClick={ () => this.editShow(docInfor) }>
              <img src={editIcon} alt="" />
            </LinkButton>
            <LinkButton onClick={ () => this.showDeleteConfirm(docInfor) }>
              <img src={deleteIcon} alt="" />
            </LinkButton>  
          </span>
          )   
      },
    ];
  }

  getDataFilelList = async() => {   // 获取 数据文件列表     
    const drill_id = getWells().drill_id;  
    const org_id = getWells().drill_org_id; 
    const ws_id = getWells().drill_ws_id;  
    this.setState({ loading: true })
    const result = await reqDataFileListById(drill_id,org_id,ws_id);  
    console.log("井id获取文件",result)
    this.setState({ loading: false })
    if(result.code === 200){
      const dataFileList = result.data;
      this.setState({
        dataFileList
      },()=>console.log("list",dataFileList)); 
    }else{
      message.error(result.data);
    }
  }

  uploadShow = () => {
    this.setState({
      visible: '1'
    })
  }

  uploadData = async() => {   // 上传文件 响应函数
    this.setState({
      visible: '0'
    }) 
    const fileData = this.fileData;
    const formData = this.state.form;   // 这里 获取到的是 纯文件

    formData.append('drill_id', getWells().drill_id);
    formData.append('org_id', getWells().drill_org_id);
    formData.append('ws_id', getWells().drill_ws_id);
    // formData['drill_id'] = getWells().drill_id;
    // formData['org_id'] = getWells().drill_org_id;
    // formData['ws_id'] = getWells().drill_ws_id;
    console.log(this.state.form,'hhhhahhaahhahha');
    if(fileData.length === 0) {
      message.warning("请选择要上传的文件!");
    }
    else{
      this.setState({ loading: true })
      Axios.defaults.baseURL='http://47.104.167.113:8081/data/management/document/upload'
      Axios({
          method: 'post',
          url: 'http://47.104.167.113:8081/data/management/document/upload',
          data: formData,
          headers: { "Content-Type": "multipart/form-data"}
      }).then(({data}) => {
        console.log("上传文件",data)
        if(data.code === 200){
          message.success("上传成功!");
          this.getDataFilelList();  // 重新获取列表
        }else{
          message.error("上传失败!");
        }
      }).catch((err) =>{
        message.error("请求失败!");
      }).finally(() =>{
        this.setState({ loading: false });
        this.setState({
          form:new FormData()
        })
      })   
    }
    
  }

  editShow = (docInfor) => {   // 编辑文件信息
    this.docInfor = docInfor;
    this.setState({
      visible: '2'
    })
  }
  editDocInfor = async(docInfor) => {   // 编辑文件信息  
    this.setState({ visible: '0' });
    const doc_id = docInfor.doc_id;
    const drill_id = docInfor.drill_id;
    const org_id = docInfor.org_id;
    const ws_id = docInfor.ws_id;
    const start_depth = this.formRef.current.getFieldValue('start_depth');
    const end_depth = this.formRef.current.getFieldValue('end_depth');
    const measuring_time = this.dateString1 == null ? docInfor.measuring_time : this.dateString1;
    const measuring_address = this.formRef.current.getFieldValue('measuring_address') ? this.formRef.current.getFieldValue('measuring_address') : '';
    const casing_depth = this.formRef.current.getFieldValue('casing_depth') ? this.formRef.current.getFieldValue('casing_depth') : '';
    const operator = this.formRef.current.getFieldValue('operator') ? this.formRef.current.getFieldValue('operator') : '';
    const remark = this.formRef.current.getFieldValue('remark') ? this.formRef.current.getFieldValue('remark') : '';
    console.log('编辑文件信息',doc_id,drill_id,org_id,ws_id,start_depth,end_depth,measuring_time,measuring_address,casing_depth,operator,remark);
    const result = await reqEditDocInfo(doc_id,drill_id,org_id,ws_id,start_depth,end_depth,measuring_time,measuring_address,casing_depth,operator,remark);
    console.log("编辑文件result",result);
    if(result.code === 200){
      message.success("修改成功！");
      // 3、重新获取列表
      this.getDataFilelList();
    }else{
      message.error("修改失败！");   
    }
  };

  // 对话框取消按钮
  handleCancel = () => {
    this.setState({
      visible: '0'
    })
  }

  
  handleDeleteOnOk = async(docInfor) => {  // 删除onOk
    this.setState({
      visible: '0'
    })
    const doc_id = docInfor.doc_id;
    const drill_id = docInfor.drill_id;
    const org_id = docInfor.org_id;
    const ws_id = docInfor.ws_id;
    const result = await reqDeleteDoc(doc_id,drill_id,org_id,ws_id); 
    //console.log("result",result)
    if(result.code === 200){
      message.success("文件已删除！");
      this.getDataFilelList();
    }else{
      message.error(result.data);
    }  
   };

  showDeleteConfirm = (docInfor) => {   // 删除响应函数
    confirm({
      title: '您确定要删除该文件吗?',
      icon: <ExclamationCircleOutlined />,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => this.handleDeleteOnOk(docInfor)  
    })
 };


  componentWillMount() {
    this.initColumns();
  }
  componentDidMount() {
    this.getDataFilelList();
  }

  render() {
    const { visible,loading,dataFileList } = this.state;
    const { location } = this.props;
    const docInfor = this.docInfor || {};
    let workshopNameLable = getWorkshop().ws_name; 
    let wellsId;
    if(location.state && location.state.wells){
      wellsId = location.state.wells.drill_id;
      setWells(this.props.location.state.wells);
    }else{
      wellsId = getWells().drill_id;  
    }

    return (
      <div className='data-mgt-wrapper'>
        <div className='data-mgt-header'>
        <div>
        <Search
            className='data-header-search'
            placeholder="根据文件名称搜索"
            enterButton="搜索"
            size="middle"
            onSearch={(value) => this.handleNameSearch(value)}
          />
          <Button type="primary" className='data-header-add' onClick={this.uploadShow}>上传数据</Button>
        </div>
          <Breadcrumb separator=">" className="data-mgt-breadcrumb">
            <Breadcrumb.Item ><Link to="/data-mgt">数据管理</Link></Breadcrumb.Item>
            <Breadcrumb.Item ><Link to="/data-mgt/showWells">{workshopNameLable}</Link></Breadcrumb.Item>
            <Breadcrumb.Item >{wellsId}</Breadcrumb.Item>
          </Breadcrumb>
        </div>
        <div className='data-mgt-content'>
          <Table
            columns={this.columns}
            dataSource={dataFileList}    //dataFileList
            size='middle'
            loading={loading}   
            pagination={false}
            locale = {{
              cancelSort:'点击取消排序',
              triggerAsc:'点击升序',
              triggerDesc:'点击降序'
            }}
          />
          <Modal
            title="上传数据文件"
            visible={visible === '1'}
            onOk={this.uploadData}
            onCancel={this.handleCancel}
            footer={null}
            // okText="上传"
            // cancelText="取消"
            destroyOnClose={true}
          >
            <UploadDatafile 
              cancel={this.handleCancel}
              // setForm = {(formRef) => {this.formRef = formRef}}
              // //setDate = {(dateString) => {this.dateString = dateString}} 
              // setFile = {(fileData,formData,type) => {
              //   this.fileData = fileData; 
              //   let form;
              //   form=this.state.form
              //   form.append(type,formData);
              //   // form[type]=formData;
              //   this.setState({
              //     form
              //   });
              // }}
            />  
            {/* <UploadForm cancel={this.handleCancel}/> */}
          </Modal>

          <Modal
            title="编辑文件信息"
            visible={visible === '2'}
            onOk={() => this.editDocInfor(docInfor)}
            onCancel={this.handleCancel}
            okText="确定"
            cancelText="取消"
            destroyOnClose={true}
          >
            <EditDataFileForm  
              docInfor = {docInfor}
              setDate = {(dateString) => {this.dateString1 = dateString}} 
              setForm = {(formRef) => {this.formRef = formRef}}  // 获取 子组件 传递过来的user对象参数
            />
          </Modal>
        </div>
      </div>
    )
  }
}

export default ShowDataMgt;